package top.lyc829.zzl_android.ui.index.serach;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import okhttp3.Response;
import top.lyc829.zzl_android.logic.bean.ResultBean;
import top.lyc829.zzl_android.logic.bean.SearchBean;
import top.lyc829.zzl_android.logic.network.Network;
import top.lyc829.zzl_android.logic.util.HttpUtil;
import top.lyc829.zzl_android.logic.util.Utils;
import top.lyc829.zzl_android.logic.util.gson.JsonUtilNew;

public class SearchViewModel extends ViewModel {
    private MutableLiveData<List<SearchBean>> SearchLiveData;

    public MutableLiveData<List<SearchBean>> getSearchLiveLiveData() {
        if (SearchLiveData == null) {
            SearchLiveData = new MutableLiveData<>();
        }
        return SearchLiveData;
    }

    public void deleteItem(int itemId) {
        List<SearchBean> searchBeans = getSearchLiveLiveData().getValue();
        if (searchBeans == null) return;
        for (SearchBean searchBean : searchBeans) {
            if (searchBean.getId() == itemId) {
                searchBeans.remove(searchBean);
                break;
            }
        }
        getSearchLiveLiveData().setValue(searchBeans);
    }


    public void getSearchLiveDataServer(int type) {

        Network.getSearchHistory(type, Utils.getUserId(), new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = Objects.requireNonNull(res.body()).string();
                ResultBean<List<SearchBean>> resultBean = JsonUtilNew.fromJsonArray(resultStr, SearchBean.class);
                if (resultBean.getCode().equals(200)) {
                    getSearchLiveLiveData().postValue(resultBean.getData());
                } else {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });
    }

    /**
     * 删除历史搜索记录
     * @param id 搜索记录id
     */
    public void EraseSearchLiveDataServer(int id) {

        Network.eraseSearchHistory(id, new HttpUtil.MyCallback() {
            @Override
            public void success(Response res) throws IOException {
                String resultStr = Objects.requireNonNull(res.body()).string();
                ResultBean<Void> resultBean = JsonUtilNew.fromJsonObject(resultStr, Void.class);
                if (!resultBean.getCode().equals(200)) {
                    failed(new IOException(resultBean.getMsg()));
                }
            }

            @Override
            public void failed(IOException e) {
                Utils.Sout(e.getMessage());
            }
        });


    }
}
